package br.zeus.lemenu

class MenuController {

    def novo = {
		def menuInstance = new Menu()
		menuInstance.properties = params
		return [menuInstance: menuInstance]
	}
	
	def salvar = {
		def menuInstance = new Menu(params)
		if(Menu.countByAtivo(true) == 0) {
			menuInstance.setAtivo(true)
		}
		
		if (menuInstance.save(flush: true)) {
			flash.message = "${message(code: 'menu.criado', args: [menuInstance.nome])}"
			redirect(action: "modificar", params: [menu: menuInstance.id])
		} else {
			render(view: "novo", model: [menuInstance: menuInstance])
		}
	}
	
	def modificar = {
		if(Menu.count() == 0) {
			flash.message = "${message(code: 'menu.atual.inexistente')}"
			redirect(action: "novo")
		}
		
		def itens = Item.list()
		def menu = Menu.get(params?.menu)
		if(menu) {
			menu.getItemIndicacao().keySet().each {
				def item = Item.findByNome(it)
				if(itens.contains(item)) {
					itens.remove(item)
				}
			}
		}
		
		[menus: Menu.list(), itens: itens, menu: menu]
	}
	
	def adicionarItem = {
		def menu = Menu.get(params.menu)
		def item = Item.get(params.item)
		if(menu && item) {
			menu.adicionarItem(item)
			menu.save(flush: true)
		}
		
		redirect(action: "modificar", params: [menu: params?.menu])
	}
	
	def excluir = {
		if(Menu.count() == 0) {
			flash.message = "${message(code: 'menu.atual.inexistente')}"
			redirect(action: "novo")
		}
		
		[menus: Menu.list()]
	}
	
	def doExcluir = {
		def menu = Menu.get(params.menu)
		if(menu) {
			def menuAtivo = Menu.findByAtivo(true)
			if(!menuAtivo.id == menu.id) {
				menu.delete(flush: true)
			} else {
				flash.message = "${message(code: 'menu.excluir.atual')}"
			}
		}
		
		redirect(action: "excluir")
	}
	
	def atual = {
		if(Menu.count() == 0) {
			flash.message = "${message(code: 'menu.atual.inexistente')}"
			redirect(action: "novo")
		}
		
		[menuAtivo: Menu.findByAtivo(true), menusDisponiveis: Menu.findAllByAtivo(false)]
	}
	
	def alterarMenuAtual = {
		def menuEscolhido = Menu.get(params.menuEscolhido)
		if(menuEscolhido) {
			def menuAtual = Menu.findByAtivo(true)
			if(menuAtual) {
				menuAtual.setAtivo(false)
				menuAtual.save(flush: true)
			}
			menuEscolhido.setAtivo(true)
			menuEscolhido.save(flush: true)
		}
		
		redirect(action: "atual")
	}
	
	def indicacoesPossiveis = {
		def item = Item.get(params.id)
		def indicacoesPossiveis = Item.createCriteria().list {
			ne("categoria", item.categoria)
		}
		
		[item: item, indicacoes: indicacoesPossiveis, menu: params.menu]
	}
	
	def indicar = {
		def menu = Menu.get(params.menu)
		def item = Item.get(params.item)
		def indicacao = Item.get(params.indicacao)
		if(item && indicacao && menu) {
			menu.adicionarItem(item, indicacao)
		}
		
		redirect(action: "modificar", params: [menu: menu.id])
	}
}
